package com.jumi.microservice.service.comment;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ExportExcelCommonResponse;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.domain.GoodsSkuInfoDTO;
import com.jumi.microservice.dto.comment.admin.*;
import com.jumi.microservice.dto.comment.commentEnum.CommentEnum;
import com.jumi.microservice.dto.comment.commentEnum.SensitiveKeywordEnum;
import com.jumi.microservice.dto.reponse.UserExternalResponse;
import com.jumi.microservice.entity.Comment;
import com.jumi.microservice.entity.SpecialKeyword;
import com.jumi.microservice.mapper.CommentMapper;
import com.jumi.microservice.mapper.SpecialKeywordMapper;
import com.jumi.microservice.service.CommodityApi;
import com.jumi.microservice.service.IMemberService;
import com.jumi.microservice.service.IUserExternalService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Scw
 * @Date 2020-08-04 17:56
 */
@Service
public class AdminSpecialService {
    private static final Logger log = LoggerFactory.getLogger(AdminSpecialService.class);
    @Resource
    private SpecialKeywordMapper specialKeywordMapper;
    @DubboReference
    private IUserExternalService iUserExternalService;
    @DubboReference
    private IMemberService iMemberService;
    @Resource
    private CommentMapper commentMapper;
    @DubboReference
    private CommodityApi goodsClient;

    /**
     * 敏感词列表
     *
     * @param sensitiveKeywordListRequest
     * @return
     */
    public TableDataInfo<SensitiveKeywordListResponse> spaecialAdminList(SensitiveKeywordListRequest sensitiveKeywordListRequest) {

        QueryWrapper<SpecialKeyword> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("is_del","0");
        //创建时间
        if (sensitiveKeywordListRequest.getCreateTime() != null && !"".equals(sensitiveKeywordListRequest.getCreateTime())) {
           /* queryWrapper.gt("creat_time", sensitiveKeywordListRequest.getCreateTime().replace("T00:00:00", "") + " 00:00:00");
            queryWrapper.le("creat_time", sensitiveKeywordListRequest.getCreateTime().replace("T00:00:00", "") + " 23:59:59");*/
            queryWrapper.le("creat_time", sensitiveKeywordListRequest.getCreateTime());
        }
        /**
         * 敏感词搜索
         */
        if (sensitiveKeywordListRequest.getSensitiveWords() != null) {
            queryWrapper.like("sensitive_words", sensitiveKeywordListRequest.getSensitiveWords());
        }

        IPage<SpecialKeyword> page = new Page<>(sensitiveKeywordListRequest.getPageNum(), sensitiveKeywordListRequest.getPageSize());
        page = specialKeywordMapper.selectPage(page, queryWrapper);

        List<SpecialKeyword> commentPage = page.getRecords();
        if(commentPage.size() == 0) {
            throw new BaseException(SensitiveKeywordEnum.COMMENT_QUERY_ID_ERROR.getCode(), SensitiveKeywordEnum.COMMENT_QUERY_ID_ERROR.getMessage());
        }
        //有序列表
        List<SensitiveKeywordListResponse> result = new ArrayList<>();
        for (SpecialKeyword comments : commentPage) {
            String userName = comments.getCreatUsername();
            String updateUserName = comments.getUpdataUsername();
            if(userName == null || userName.equals("")){
                //查询创建用户名
                Integer uid = comments.getCreatUser().intValue();
                if(uid !=null){
                    UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(uid);
                    log.debug("\n\n\n------敏感词列表----【查询创建用户名】:[{}]", JSON.toJSONString(userExternalResponse));
                    if (userExternalResponse != null) {
                        userName = userExternalResponse.getNickName();
                        comments.setCreatUsername(userName);
                    }
                }
            }

            if(updateUserName == null || updateUserName.equals("")){
                //查询更新用户名
                Integer uidUp = comments.getUpdataUser().intValue();
                if(uidUp !=null){
                    UserExternalResponse userUpExternalResponse = iUserExternalService.getUserByUid(uidUp);
                    log.debug("\n\n\n------敏感词列表----【查询更新用户名】:[{}]", JSON.toJSONString(userUpExternalResponse));
                    if (userUpExternalResponse != null) {
                        updateUserName = userUpExternalResponse.getNickName();
                        comments.setUpdataUsername(updateUserName);
                    }
                }
            }

            SensitiveKeywordListResponse sensitiveKeywordListResponse = new SensitiveKeywordListResponse();
            BeanUtils.copyProperties(comments, sensitiveKeywordListResponse);
            sensitiveKeywordListResponse.setCreatUser(comments.getCreatUser().intValue());
            sensitiveKeywordListResponse.setUpdataUser(comments.getUpdataUser().intValue());
            result.add(sensitiveKeywordListResponse);
        }

        TableDataInfo<SensitiveKeywordListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(page.getTotal());
        return dataInfo;

    }

    /**
     * 状态
     * @param  '0':开启 1关闭
     * @param sensitiveStatusRequest
     * @return
     */
    public Boolean editSpecialStatus(SensitiveStatusRequest sensitiveStatusRequest,Long uid,String name) {
        boolean result = false;

        Integer commentId = sensitiveStatusRequest.getId();
        if(commentId == null){
            throw new BaseException(SensitiveKeywordEnum.COMMENT_STATUS_ID_ERROR.getCode(), SensitiveKeywordEnum.COMMENT_STATUS_ID_ERROR.getMessage());
        }else{
            SpecialKeyword specialKeyword = new SpecialKeyword();
            BeanUtils.copyProperties(sensitiveStatusRequest, specialKeyword);
            specialKeyword.setUpdataTime(new Date());
            specialKeyword.setUpdataUser(uid);
            specialKeyword.setUpdataUsername(name);
            int row = specialKeywordMapper.updateById(specialKeyword);
            if (row > 0) {
                //返回 状态
                result = true;
            }
        }
        return result;
    }

    /**
     * 删除
     * @param sensitiveKeywordDelRequest
     * @return
     */
    public  Boolean isdelSpecial(SensitiveKeywordDelRequest sensitiveKeywordDelRequest){
        boolean result = false;
        Integer spacieId = sensitiveKeywordDelRequest.getId();
        if(spacieId == null){
            throw new BaseException(SensitiveKeywordEnum.COMMENT_STATUS_ID_ERROR.getCode(), SensitiveKeywordEnum.COMMENT_STATUS_ID_ERROR.getMessage());
        }else{
            //查询信息
            QueryWrapper<SpecialKeyword> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", spacieId);
            SpecialKeyword specialKeys = specialKeywordMapper.selectOne(queryWrapper);
            if (specialKeys == null) {
                throw new BaseException(SensitiveKeywordEnum.KEYWORD_DEL_ID_ERROR.getCode(), SensitiveKeywordEnum.KEYWORD_DEL_ID_ERROR.getMessage());
            }

            SpecialKeyword specialDel = new SpecialKeyword();
            BeanUtils.copyProperties(sensitiveKeywordDelRequest, specialDel);
            int rows = specialKeywordMapper.updateById(specialDel);
            if (rows > 0) {
                //返回 状态
                result = true;
            }
        }
        return result;
    }


    /**
     * 编辑敏感词
     * @param sensitiveKeywordRequest
     * @return
     */
    public Boolean editSensitive(SensitiveKeywordRequest sensitiveKeywordRequest) {
        boolean result = false;
        //获取当前用户ID
        Long userId = sensitiveKeywordRequest.getUpdataUser();
        if (userId == null) {
            throw new BaseException(SensitiveKeywordEnum.NO_LOGIN.getCode(), SensitiveKeywordEnum.NO_LOGIN.getMessage());
        }
        log.info("\n\n\n------编辑敏感词----【查询编辑用户名】:[{}]", JSON.toJSONString(sensitiveKeywordRequest.getUpdataUsername()));
        log.info("\n------编辑敏感词----【查询编辑用户ID】:[{}]", JSON.toJSONString(userId));
        Integer commentId = sensitiveKeywordRequest.getId();
        if(commentId == null){
            throw new BaseException(SensitiveKeywordEnum.COMMENT_STATUS_ID_ERROR.getCode(), SensitiveKeywordEnum.COMMENT_STATUS_ID_ERROR.getMessage());
        }else{
            //查询信息
            QueryWrapper<SpecialKeyword> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sensitive_words", sensitiveKeywordRequest.getSensitiveWords()).eq("is_del",0);
            int count = specialKeywordMapper.selectCount(queryWrapper);
            if (count >= 1) {
                throw new BaseException(SensitiveKeywordEnum.KEYWORD_INSERT_REPEAT_ERROR.getCode(), SensitiveKeywordEnum.KEYWORD_INSERT_REPEAT_ERROR.getMessage());
            }
            //查询信息
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", commentId);
            SpecialKeyword specialKeys = specialKeywordMapper.selectOne(queryWrapper);
            if (specialKeys == null) {
                throw new BaseException(SensitiveKeywordEnum.COMMENT_QUERY_ID_ERROR.getCode(), SensitiveKeywordEnum.COMMENT_QUERY_ID_ERROR.getMessage());
            }

            SpecialKeyword specialKeyword = new SpecialKeyword();
            BeanUtils.copyProperties(sensitiveKeywordRequest, specialKeyword);
            specialKeyword.setUpdataUsername(sensitiveKeywordRequest.getUpdataUsername());
            specialKeyword.setUpdataUser(sensitiveKeywordRequest.getUpdataUser());
            specialKeyword.setUpdataTime(new Date());
            int row = specialKeywordMapper.updateById(specialKeyword);
            if (row > 0) {
                //返回 状态
                result = true;
            }
        }
        return result;
    }

    /**
     * 添加敏感词
     * @param sensitiveKeywordRequest
     * @return
     */
    public Boolean addSpecial(SensitiveKeywordRequest sensitiveKeywordRequest) {
        //获取当前用户ID
        Long userId = sensitiveKeywordRequest.getCreatUser();
        if (userId == null) {
            throw new BaseException(SensitiveKeywordEnum.NO_LOGIN.getCode(), SensitiveKeywordEnum.NO_LOGIN.getMessage());
        }
        log.info("\n\n\n------编辑敏感词----【查询添加用户名】:[{}]", JSON.toJSONString(sensitiveKeywordRequest.getCreatUsername()));
        log.info("\n------编辑敏感词----【查询添加用户ID】:[{}]", JSON.toJSONString(userId));
        String content = sensitiveKeywordRequest.getSensitiveWords().trim();
        //查询信息
        QueryWrapper<SpecialKeyword> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sensitive_words", content).eq("is_del",0);
        int count = specialKeywordMapper.selectCount(queryWrapper);
        if (count >= 1) {
            throw new BaseException(SensitiveKeywordEnum.KEYWORD_INSERT_REPEAT_ERROR.getCode(), SensitiveKeywordEnum.KEYWORD_INSERT_REPEAT_ERROR.getMessage());
        }
        sensitiveKeywordRequest.setSensitiveWords(content);
        //entity
        SpecialKeyword specialKeyword = new SpecialKeyword();
        BeanUtils.copyProperties(sensitiveKeywordRequest, specialKeyword);
        //拼接上uid
        //sensitiveKeywordRequest.setCreatUser(userId);

        return specialKeywordMapper.insert(specialKeyword) > 0;
    }

    /**
     * 导出excel
     */
    public ExportExcelCommonResponse<SensitiveExportResponse> exportExcel(SenitiveExportRequest request){
        QueryWrapper<SpecialKeyword> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("creat_time");
        if (request.getSensitiveWords() != null) {
            queryWrapper.like("sensitive_words", request.getSensitiveWords());
        }
        //创建时间
        if (request.getCreateTime() != null && !"".equals(request.getCreateTime())) {
            queryWrapper.gt("creat_time", request.getCreateTime().replace("T00:00:00", "") + " 00:00:00");
            queryWrapper.le("creat_time", request.getCreateTime().replace("T00:00:00", "") + " 23:59:59");
        }
        queryWrapper.eq("is_del",0);
        List<SpecialKeyword> userCashes = specialKeywordMapper.selectList(queryWrapper);
        if(userCashes.size() == 0){
            return null;
        }
        List<SensitiveExportResponse> list = new ArrayList<>();
        userCashes.forEach(userCash -> {
            SensitiveExportResponse sensitiveExportResponse = new SensitiveExportResponse();
            BeanUtils.copyProperties(userCash, sensitiveExportResponse);
            list.add(sensitiveExportResponse);
        });
        ExportExcelCommonResponse<SensitiveExportResponse> response = new ExportExcelCommonResponse<>();
        response.setData(list);
        response.setFileName(System.currentTimeMillis() + ".xlsx");
        return response;
    }

    /**
     * 导入
     */
    public boolean ExcelImportHandler(List<SenitiveImplodRequest> list,String name,Long uid) {
        if(list.isEmpty()){
            return false;
        }
        List<SpecialKeyword> specialWords = new ArrayList<>();
        List<String> keyWordsList = new ArrayList<>();
        //查询信息
        QueryWrapper<SpecialKeyword> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("sensitive_words", list.stream().map(SenitiveImplodRequest::getSensitiveWords)
                .collect(Collectors.toList())).eq("is_del",0);
        List<String> result = specialKeywordMapper.selectList(queryWrapper).stream().map(SpecialKeyword::getSensitiveWords)
                .collect(Collectors.toList());
        for(SenitiveImplodRequest senitiveImplodRequest:list){
            if(keyWordsList.contains(senitiveImplodRequest.getSensitiveWords())
                    || result.contains(senitiveImplodRequest.getSensitiveWords())){
                continue;
            }
            if(senitiveImplodRequest.getSensitiveWords()==null || senitiveImplodRequest.getSensitiveWords().trim().isEmpty()){
                continue;
            }

            SpecialKeyword specialkeys = new SpecialKeyword();
            BeanUtils.copyProperties(senitiveImplodRequest,specialkeys);
            specialkeys.setCreatUsername(name);
            specialkeys.setCreatUser(uid);
            specialWords.add(specialkeys);
            keyWordsList.add(senitiveImplodRequest.getSensitiveWords());
        }
        int res = 0;
        if(!specialWords.isEmpty()){
            res =  specialKeywordMapper.updateSend(specialWords);
        }
        return res >0;
    }
    /**
     * 评论列表
     *
     * @param commentListRequest
     * @return
     */
    public TableDataInfo<CommentListResponse> commentsAdminList(CommentListRequest commentListRequest) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        /*敏感词查询*/
        if (commentListRequest.getSensitiveWords() != null && !"".equals(commentListRequest.getSensitiveWords())) {
            queryWrapper.like("content", commentListRequest.getSensitiveWords());
        }
        /*商品名搜索*/
        log.debug("\n\n\n\n\n---------评论列表[商品名搜索]:[{}]", JSON.toJSONString(commentListRequest.getGoodName()));
        if (commentListRequest.getGoodName() != null && !"".equals(commentListRequest.getGoodName())) {
            //根据商品查询商品id 返回
            String goodName = commentListRequest.getGoodName().trim();
            /*调用商品接口返回商品id*/
            Map<Long, String> getGoodsSkuIdByName = goodsClient.getGoodsSkuIdByName(goodName);
            if (getGoodsSkuIdByName != null) {
                Set<Long> skuIds = getGoodsSkuIdByName.keySet();
                log.debug("评论列表------【调用商品接口返回商品skuIds】:[{}]", JSON.toJSONString(skuIds));
                if (!skuIds.isEmpty()) {
                    queryWrapper.in("gid", skuIds);
                } else {
                    return new TableDataInfo<>();
                }
            }
        }
        //创建开始时间
        if (commentListRequest.getBeginTime() != null && !"".equals(commentListRequest.getBeginTime())) {
            queryWrapper.ge("create_time", commentListRequest.getBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //创建结束时间
        if (commentListRequest.getEndTime() != null && !"".equals(commentListRequest.getEndTime())) {
            queryWrapper.le("create_time", commentListRequest.getEndTime().replace("T00:00:00", "") + " 23:59:59");
        }

        if (commentListRequest.getProductSatisfaction() != null) {
            List<Integer> satisAverage = new ArrayList<Integer>();

            switch (commentListRequest.getProductSatisfaction()) {
                case 1:
                    satisAverage.add(1);
                    queryWrapper.in("product_satisfaction", satisAverage);//差评
                    break;
                case 2:
                    satisAverage.add(2);
                    satisAverage.add(3);
                    queryWrapper.in("product_satisfaction", satisAverage);
                    break;
                case 3:
                    satisAverage.add(4);
                    satisAverage.add(5);
                    queryWrapper.in("product_satisfaction", satisAverage);
                    break;
                default:
                    break;
            }
        }
        IPage<Comment> page = new Page<>(commentListRequest.getPageNum(), commentListRequest.getPageSize());
        page = commentMapper.selectPage(page, queryWrapper);
        List<Comment> commentPage = page.getRecords();
        log.debug("评论列表------【commentPage】:[{}]", JSON.toJSONString(commentPage));
        //有序列表
        List<CommentListResponse> result = new ArrayList<>();
        if (commentPage == null||commentPage.size()==0) {
            return new TableDataInfo<>();
        }
        //根据商品ID--sku查询商品主图【商品服务提供接口】
        List<Long> skuIds = new ArrayList<>();
        List<GoodsSkuInfoDTO> getGoodsSkuInfoByIds = new ArrayList<>();
        for (Comment comments : commentPage) {
            skuIds.add(comments.getGid().longValue());
        }
        if (skuIds.size() > 0) {
            log.debug("评论列表------【sku查询商品主图】:[{}]", JSON.toJSONString(skuIds));
            getGoodsSkuInfoByIds = goodsClient.getGoodsSkuInfoByIds(skuIds);
        }
        log.debug("评论列表------【根据商品ID--sku查询商品主图】:[{}]", JSON.toJSONString(getGoodsSkuInfoByIds));
        for (Comment comments : commentPage) {
            String userName = comments.getUserName();
            if (userName == null || userName.equals("")) {
                //查询用户名
                Integer uid = comments.getUid().intValue();
                if (uid != null) {
                    UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(uid);
                    log.debug("后台评论列表----【用户的所有信息】:[{}]", JSON.toJSONString(userExternalResponse));
                    if (userExternalResponse != null) {
                        userName = userExternalResponse.getNickName();
                        comments.setUserName(userName);
                    }
                }
            }

            CommentListResponse commentListResponse = new CommentListResponse();
            BeanUtils.copyProperties(comments, commentListResponse);

            //设置商品名称
            if (getGoodsSkuInfoByIds != null) {
                getGoodsSkuInfoByIds.forEach(
                        getGoodsSkuInfo -> {
                            if (comments.getGid().longValue() == getGoodsSkuInfo.getId()) {
                                commentListResponse.setGidTitle(getGoodsSkuInfo.getGoodsName());
                                log.debug("后台评论列表----【GidTitle】:[{}]", JSON.toJSONString(commentListResponse.getGidTitle()));
                            }
                        }
                );

            }
            log.debug("后台评论列表----【commentListResponse】:[{}]", JSON.toJSONString(commentListResponse));
            result.add(commentListResponse);
        }
        TableDataInfo<CommentListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(page.getTotal());
        return dataInfo;

    }

    /**
     * 是否隐藏
     *
     * @param '0':否              1是
     * @param commentHideRequest
     * @return
     */
    public Boolean editHide(CommentHideRequest commentHideRequest) {
        boolean result = false;
        Integer commentId = commentHideRequest.getId();
        if (commentId == null) {
            throw new BaseException(CommentEnum.COMMENT_HIDEN_ID_ERROR.getCode(), CommentEnum.COMMENT_HIDEN_ID_ERROR.getMessage());
        } else {
            Comment comment = new Comment();
            BeanUtils.copyProperties(commentHideRequest, comment);

            int row = commentMapper.updateById(comment);
            if (row > 0) {
                //返回 状态
                result = true;
            }
        }
        return result;
    }

    /**
     * 回复内容
     *
     * @param commentReplyRequest
     * @return
     */
    public Boolean editReply(CommentReplyRequest commentReplyRequest) {
        boolean result = false;

        Integer commentId = commentReplyRequest.getId();
        if (commentId == null) {
            throw new BaseException(CommentEnum.COMMENT_HIDEN_ID_ERROR.getCode(), CommentEnum.COMMENT_HIDEN_ID_ERROR.getMessage());
        } else {
            String reply = commentReplyRequest.getReply().trim();
            log.debug("评论列表------【回复内容】:[{}]", JSON.toJSONString(reply));
            //字数限制
            if (reply.length() > 200 || reply == null) {
                throw new BaseException(CommentEnum.COMMENT_REPLY_LONG.getCode(), CommentEnum.COMMENT_REPLY_LONG.getMessage());
            }

            Comment comment = new Comment();
            BeanUtils.copyProperties(commentReplyRequest, comment);

            int row = commentMapper.updateById(comment);
            if (row > 0) {
                //返回 状态
                result = true;
            }
        }
        return result;

    }

}
